package com.xebest.web.controller.venmanager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xebest.api.dto.ParameterDTO;
import com.xebest.api.dto.XeVenInfoRequestDTO;
import com.xebest.api.dto.XeVenInfoResponseDTO;
import com.xebest.api.service.XeVenInfoApiService;
import com.xebest.common.base.controller.BASEMessage;
import com.xebest.common.base.controller.BaseController;
import com.xebest.common.base.controller.BaseResponse;
import com.xebest.common.base.dto.BaseResponseDTO;
import com.xebest.common.util.HttpClientUtil;
import com.xebest.common.util.XeBaseUtil;
import com.xebest.common.util.XeRedisUtil;
import com.xebest.config.SmsConfig;
import com.xebest.constant.XeRedisKey;
import com.xebest.constant.XeSmsConstans;
import com.xebest.util.SmsConstants;
import com.xebest.web.form.VenInfoParamForm;
import com.xebest.web.form.XeVenInfoForm;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 商户入驻相关
 *
 * @author shihui
 */
@Controller
@RequestMapping("/xeveninfo")
public class XeVenInfoController extends BaseController {

    private static Logger log = LoggerFactory
            .getLogger(XeVenInfoController.class);

    @Autowired
    private XeVenInfoApiService xeVenInfoApiService;
    @Autowired
    private Environment env;
    @Autowired
    private SmsConfig smsConfig;

    /**
     * 商户入驻信息保存接口
     *
     * @author shihui
     */
    @RequestMapping("/merchantsSettled")
    @ResponseBody
    public BaseResponse merchantsSettled(
            @RequestBody @Validated XeVenInfoForm xeVenInfoForm,
            BindingResult result, String zoom) {
        log.info("商户入驻--商户入驻信息保存--start：参数xeVenInfoForm"
                + JSONObject.toJSONString(xeVenInfoForm) + ";zoom:" + zoom);
        try {
            JSONObject userInfo = super.getErpLoginUserInfo();
            log.info("商户入驻--登录信息" + userInfo);
            if (userInfo == null) {
                return sendAjaxError("请先登录");
            }
            if (result.hasErrors()) {
                String errorsMag = result.getFieldError().getDefaultMessage();
                return sendAjaxError(errorsMag);
            }
            // 封装对象
            String userId = userInfo.getString("purchaserUserId");
            if (StringUtils.isBlank(userId)) {
                return sendAjaxError("登录状态异常，userId为空");
            }
            // 校验验证码
            boolean resMsg =
                    XeBaseUtil.baseUtil.checkVerifyCodeByMobileAndSmsNo(xeVenInfoForm.getVerifyCode(), XeSmsConstans.XE_RUZHU_SMS, xeVenInfoForm.getUserPhone());
            if (!resMsg) {
                return sendAjaxError("验证码有误");
            }
            String key = XeRedisKey.XE_VEN_SMS_KEY + xeVenInfoForm.getUserPhone();
            XeRedisUtil.redisUtil.delete(key);
            XeVenInfoRequestDTO dto = JSON.parseObject(JSON.toJSONString(xeVenInfoForm), XeVenInfoRequestDTO.class);
            dto.setUserId(userId);
            dto.setCreateUser(userInfo.getString("loginName"));
            if (xeVenInfoForm.isAreaFlag()) {
                List<Integer> areaId = new ArrayList<>();
                areaId.add(0);
                dto.setAreaId(areaId);
            }
            BaseResponseDTO baseResponseDTO = xeVenInfoApiService.merchantsSettled(dto);
            if (!"2000".equals(baseResponseDTO.getStatus())) {
                return sendAjaxError(baseResponseDTO.getMsg());
            }
            return sendAjaxOK();
        } catch (Exception e) {
            log.error("商户入驻--商户入驻信息保存接口,异常:{}", e);
            return sendAjaxError();
        }
    }

    /**
     * 商户入驻信息回显
     *
     * @author shihui
     */
    @RequestMapping("/getMerchantsInfo")
    @ResponseBody
    public BaseResponse getMerchantsInfo() {
        log.info("商户入驻--商户入驻信息回显--start：");
        try {
            JSONObject userInfo = super.getErpLoginUserInfo();
            if (userInfo == null) {
                return sendAjaxError("用户未登录");
            }
            ParameterDTO parameterDTO = new ParameterDTO();
            String userId = userInfo.getString("purchaserUserId");
            if (StringUtils.isBlank(userId)) {
                return sendAjaxError("登录状态异常，userId为空");
            }
            parameterDTO.setUserId(userId);
            XeVenInfoResponseDTO xeVenInfoResponseDTO = xeVenInfoApiService.getMerchantsInfo(parameterDTO);
            if (!"2000".equals(xeVenInfoResponseDTO.getStatus())) {
                return sendAjaxError(xeVenInfoResponseDTO.getMsg());
            }

            XeVenInfoForm xeVenInfoForm = JSON.parseObject(JSON.toJSONString(xeVenInfoResponseDTO), XeVenInfoForm.class);
            Map<String, Object> resMap = new HashMap<>();
            resMap.put("xeVenInfo", xeVenInfoForm);
            resMap.put("picServer", env.getProperty("erp.imgUrl"));
            return sendAjaxOK(resMap);
        } catch (Exception e) {
            log.error("商户入驻--商户入驻信息保存接口,异常:{}", e);
            return sendAjaxError();
        }
    }

    /**
     * 商户入驻信息修改保存接口
     *
     * @author shihui
     */
    @RequestMapping("/updateMerchants")
    @ResponseBody
    public BaseResponse updateMerchants( @RequestBody @Validated XeVenInfoForm xeVenInfoForm, BindingResult result, HttpServletRequest req, String zoom) {
        log.info("商户入驻--商户入驻信息修改保存接口--start：参数xeVenInfoForm" + JSONObject.toJSONString(xeVenInfoForm) + ";zoom:" + zoom);
        try {
            JSONObject userInfo = super.getErpLoginUserInfo();
            if (userInfo == null) {
                return sendAjaxError("请先登录");
            }
            if (result.hasErrors()) {
                String errorsMag = result.getFieldError().getDefaultMessage();
                return sendAjaxError(errorsMag);
            }
            boolean param = xeVenInfoForm.getVersion() != null && xeVenInfoForm.getIdcardApId() != null && xeVenInfoForm.getIdcardVer() != null;
            if (!param) {
                return sendAjaxError("缺少必要参数");
            }
            String userId = userInfo.getString("purchaserUserId");
            if (StringUtils.isBlank(userId)) {
                return sendAjaxError("登录状态异常，userId为空");
            }
            // 校验验证码
            boolean resMsg = XeBaseUtil.baseUtil.checkVerifyCodeByMobileAndSmsNo(xeVenInfoForm.getVerifyCode(), XeSmsConstans.XE_RUZHU_SMS, xeVenInfoForm.getUserPhone());
            if (!resMsg) {
                return sendAjaxError("验证码有误");
            }
            String key = XeRedisKey.XE_VEN_SMS_KEY + xeVenInfoForm.getUserPhone();
            XeRedisUtil.redisUtil.delete(key);
            // 封装对象
            XeVenInfoRequestDTO dto = JSON.parseObject(JSON.toJSONString(xeVenInfoForm), XeVenInfoRequestDTO.class);
            dto.setUserId(userId);
            dto.setCreateUser(userInfo.getString("loginName"));
            if (xeVenInfoForm.isAreaFlag()) {
                List<Integer> areaId = new ArrayList<>();
                areaId.add(0);
                dto.setAreaId(areaId);
            }
            BaseResponseDTO baseResponseDTO = xeVenInfoApiService.updateMerchants(dto);
            if (!"2000".equals(baseResponseDTO.getStatus())) {
                return sendAjaxError(baseResponseDTO.getMsg());
            }
            return sendAjaxOK();
        } catch (Exception e) {
            log.error("商户入驻--商户入驻信息保存接口,异常:{}", e);
            return sendAjaxError();
        }
    }

    /**
     * 根据城市id查询所有子集城市 -1 查询国家 0 查询所有省 省id 查询所有市 市id 查询所有区
     *
     * @author shihui
     */
    @RequestMapping("/getArea")
    @ResponseBody
    public BaseResponse getArea(HttpServletRequest req) {
        try {
            JSONObject obj = requstPayloadToJson(req);
            Integer areaId = obj.getInteger("areaId");
            log.info("商户入驻--根据父类id获取省市区--start：", areaId);
            if (areaId == null) {
                return sendAjaxError("areaId不能为空");
            }
            JSONArray json = XeBaseUtil.baseUtil.getChildArea(areaId);
            Map<String, Object> resMap = new HashMap<>();
            resMap.put("areaList", json);
            return sendAjaxOK(resMap);
        } catch (Exception e) {
            log.error("商户入驻--根据父类id获取省市区,异常:{}", e);
            return sendAjaxError();
        }
    }

    /**
     * 获取一级分类
     *
     * @author shihui
     */
    @RequestMapping("/getCategory")
    @ResponseBody
    public BaseResponse getCategory() {
        log.info("商户入驻--获取一级分类--start：");
        try {
            JSONArray json = XeBaseUtil.baseUtil.getChildCategory("0");
            Map<String, Object> resMap = new HashMap<>();
            resMap.put("categoryList", json);
            return sendAjaxOK(resMap);
        } catch (Exception e) {
            log.error("商户入驻--获取一级分类,异常:{}", e);
            return sendAjaxError();
        }
    }

    /**
     * 发送短信验证码
     *
     * @author shihui
     */
    @RequestMapping("/sendSms")
    @ResponseBody
    public BaseResponse sendSms(@RequestBody VenInfoParamForm form) {
        log.info("商户入驻--发送短信验证码--start：" + JSONObject.toJSONString(form));
        try {
            String key = XeRedisKey.XE_VEN_SMS_KEY + form.getUserPhone();
            boolean flag = XeRedisUtil.redisUtil.exists(key);
            if (flag) {
                return sendAjaxError("验证码已发送，如需重发请稍后再试！");
            }
            JSONObject userInfo = super.getErpLoginUserInfo();
            if (userInfo == null) {
                return sendAjaxError("请先登录");
            }
            String mobile = form.getUserPhone();
            if (StringUtils.isBlank(mobile)) {
                return sendAjaxError("电话号码不能为空");
            }
            StringBuffer sb = new StringBuffer();
            sb.append("mobileNO=").append(mobile).append("&merchantKey=")
                    .append(smsConfig.getMerchantKey());
            String verifyString = XeBaseUtil.baseUtil.getKeyedDigest(
                    sb.toString(), SmsConstants.MSG_MERCHANT_KEY);
            JSONObject smsJson = new JSONObject();
            smsJson.put("mobileNO", mobile);
            smsJson.put("sendSource", "ERP商户入驻");
            smsJson.put("smsNO", XeSmsConstans.XE_RUZHU_SMS);
            smsJson.put("verifyString", verifyString);
            smsJson.put("lostTime", "20");
            log.info("商户入驻短信验证码发送参数--：" + JSONObject.toJSONString(smsJson));
            String respon = HttpClientUtil.postJSON(smsConfig.getSmsUrl(),
                    smsJson);
            log.info("商户入驻短信验证码发送接口地址--：" + smsConfig.getSmsUrl());
            if (StringUtils.isBlank(respon)) {
                return sendAjaxError("发送失败");
            }
            JSONObject jsStr = JSONObject.parseObject(respon);
            String msg = jsStr.getString("msg");
            String status = jsStr.getString("status");
            log.info("商户入驻短信验证码出参--status=" + status + "msg=" + msg);
            Map<String, Object> map = new HashMap<>();
            if (!BASEMessage.SUCCESS.getStatus().equals(status)) {
                return sendAjaxError(msg);
            }
            XeRedisUtil.redisUtil.setex(key, "no", 120, TimeUnit.SECONDS);
            map.put("msg", "发送成功");
            return sendAjaxOK(map);
        } catch (Exception e) {
            log.error("商户入驻--发送短信验证码,异常:{}", e);
            return sendAjaxError();
        }
    }

    /**
     * 校验企业名称是否重复
     *
     * @author shihui
     */
    @RequestMapping("/venNameCheck")
    @ResponseBody
    public BaseResponse venNameCheck(@RequestBody VenInfoParamForm form) {
        log.info("商户入驻--校验企业名称是否重复--start：" + JSONObject.toJSONString(form));
        try {
            JSONObject userInfo = super.getErpLoginUserInfo();
            if (userInfo == null) {
                return sendAjaxError("请先登录");
            }
            String venName = form.getVenName();
            if (StringUtils.isBlank(venName)) {
                return sendAjaxError("企业名称不能为空");
            }
            ParameterDTO dto = new ParameterDTO();
            dto.setVenName(venName);
            BaseResponseDTO baseResponseDTO = xeVenInfoApiService
                    .venNameCheck(dto);
            if (!"2000".equals(baseResponseDTO.getStatus())) {
                return sendAjaxError(baseResponseDTO.getMsg());
            }
            if ("n".equals(baseResponseDTO.getMsg())) {
                return sendRemoteAjaxError("该企业名称重复，不可用");
            }
            return sendRemoteAjaxOK();
        } catch (Exception e) {
            log.error("商户入驻--校验企业名称是否重复,异常:{}", e);
            return sendAjaxError();
        }
    }

    /**
     * 校验店铺名称是否重复
     *
     * @author shihui
     */
    @RequestMapping("/shopNameCheck")
    @ResponseBody
    public BaseResponse shopNameCheck(@RequestBody VenInfoParamForm form) {
        log.info("商户入驻--校验店铺名称是否重复--start：" + JSONObject.toJSONString(form));
        try {
            JSONObject userInfo = super.getErpLoginUserInfo();
            if (userInfo == null) {
                return sendAjaxError("请先登录");
            }
            String shopName = form.getShopName();
            if (StringUtils.isBlank(shopName)) {
                return sendAjaxError("店铺名称不能为空");
            }
            ParameterDTO dto = new ParameterDTO();
            dto.setShopName(shopName);
            String userId = userInfo.getString("purchaserUserId");
            dto.setUserId(userId);
            BaseResponseDTO baseResponseDTO = xeVenInfoApiService
                    .shopNameCheck(dto);
            if (!"2000".equals(baseResponseDTO.getStatus())) {
                return sendAjaxError(baseResponseDTO.getMsg());
            }
            if ("n".equals(baseResponseDTO.getMsg())) {
                return sendRemoteAjaxError("该店铺名称重复，不可用");
            }
            return sendRemoteAjaxOK();
        } catch (Exception e) {
            log.error("商户入驻--校验店铺名称是否重复,异常:{}", e);
            return sendAjaxError();
        }
    }
}
